package com.ljfiction.book.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ljfiction.book.Baner.BookCommentBean;
import com.ljfiction.book.Baner.HotConmmentBean;
import com.ljfiction.book.MyView.ContainsEmojiEditText;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.R;
import com.ljfiction.book.adapter.BookShupingAdapter;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.SoftHideKeyBoardUtil;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.EventTool;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.Tool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class AuthShuPingActivity extends BaseActivity {

    @BindView(R.id.back_UserShuping)
    ImageView backUserShuping;
    @BindView(R.id.hotrecycle)
    RecyclerView hotrecycle;
    @BindView(R.id.timenum)
    TextView timenum;
    @BindView(R.id.timerecycle)
    RecyclerView timerecycle;
    @BindView(R.id.tocommentshuping)
    ContainsEmojiEditText tocommentshuping;
    @BindView(R.id.sendshuping)
    TextView sendshuping;
    @BindView(R.id.refresh_bookdatasmuchshuping)
    SmartRefreshLayout refreshBookdatasmuchshuping;
    @BindView(R.id.authshupingtop)
    RelativeLayout authshupingtop;
    private String bookId;
    private BookCommentBean bookCommentBean;
    private List<BookCommentBean.DataBean.ListBean> hotlist = new ArrayList<>();
    private List<BookCommentBean.DataBean.ListBean> timelist = new ArrayList<>();
    private BookShupingAdapter hotAdapter;
    private BookShupingAdapter timeAdapter;
    private Intent intentImage, intentShuping;
    private String bookName;
    private int page = 1;
    private HotConmmentBean hotbookconbean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auth_shu_qing);
        ButterKnife.bind(this);
        SoftHideKeyBoardUtil.assistActivity(this);
        authshupingtop.getBackground().setAlpha(255);
        bookId = getIntent().getStringExtra("bookId");
        bookName = getIntent().getStringExtra("bookName");
        intentImage = new Intent(this, UserCenterActivity.class);
        intentShuping = new Intent(this, ShupingDatasActivity.class);
        intView();
        initData();
        initDataHot();

    }

    private void initData() {
        OkHttpUtils.post(HttpManager.IP + "/comm-getcomminfo")

                .params("id", bookId)
                .params("type", "1")
                .params("startPage", String.valueOf(page))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        refreshBookdatasmuchshuping.finishRefresh();
                        refreshBookdatasmuchshuping.finishLoadMore();
                        Gson gson = new Gson();
                        try {
                            bookCommentBean = gson.fromJson(s, BookCommentBean.class);
                            if (200 == bookCommentBean.getReturnCode()) {
                                timelist.addAll(bookCommentBean.getData().getList());
                                timenum.setText("(" + String.valueOf(bookCommentBean.getData().getTotal()) + ")");
                                timeAdapter.notifyDataSetChanged();
                            } else {

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                });
    }

    private void intView() {
        hotAdapter = new BookShupingAdapter(R.layout.usershuping_item, hotlist);
        timeAdapter = new BookShupingAdapter(R.layout.usershuping_item, timelist);
        hotrecycle.setAdapter(hotAdapter);
        hotrecycle.setLayoutManager(new LinearLayoutManager(this));
        hotrecycle.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        timerecycle.setAdapter(timeAdapter);
        timerecycle.setLayoutManager(new LinearLayoutManager(this));
        timerecycle.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        hotAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                intentShuping.putExtra("thisshuping", hotlist.get(position));
                startActivity(intentShuping);
            }
        });
        hotAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
                switch (view.getId()) {
                    case R.id.usershuping_muimage:
                        intentImage.putExtra("userId", String.valueOf(hotlist.get(position).getUserId()));
                        startActivityForResult(intentImage,9);

                        break;
                    case R.id.userdianzanimage:
                        if (!UserManageBean.isLogin(AuthShuPingActivity.this)) {
                            return;
                        }
                        OkHttpUtils.post(HttpManager.IP + "/comm-GiveThumbs")

                                .params("commentId", hotlist.get(position).getId())
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(s);
                                            if (jsonObject.getInt("returnCode") == 200) {
                                                if (hotlist.get(position).getIsthumbs() == 0) {
                                                    hotlist.get(position).setIsthumbs(1);
                                                    hotlist.get(position).setThumbsCount(hotlist.get(position).getThumbsCount() + 1);
                                                } else {
                                                    hotlist.get(position).setIsthumbs(0);
                                                    hotlist.get(position).setThumbsCount(hotlist.get(position).getThumbsCount() - 1);
                                                }
                                                hotAdapter.notifyDataSetChanged();
                                            }else if (jsonObject.getInt("returnCode") == 400){
                                                Intent intent=new Intent(AuthShuPingActivity.this, LoginActivity.class);
                                                startActivity(intent);
                                                showToast(jsonObject.getString("msg"));
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                });
                        break;
                }
            }
        });
        timeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                intentShuping.putExtra("thisshuping", timelist.get(position));
                startActivityForResult(intentShuping, 8);
            }
        });
        timeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
                switch (view.getId()) {
                    case R.id.usershuping_muimage:
                        intentImage.putExtra("userId", String.valueOf(timelist.get(position).getUserId()));
                        startActivity(intentImage);
                        break;
                    case R.id.userdianzanimage:
                        if (!UserManageBean.isLogin(AuthShuPingActivity.this)) {
                            return;
                        }
                        OkHttpUtils.post(HttpManager.IP + "/comm-GiveThumbs")

                                .params("commentId", String.valueOf(timelist.get(position).getId()))
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(s);
                                            if (jsonObject.getInt("returnCode") == 200) {
                                                if (timelist.get(position).getIsthumbs() == 0) {
                                                    timelist.get(position).setIsthumbs(1);
                                                    timelist.get(position).setThumbsCount(timelist.get(position).getThumbsCount() + 1);
                                                } else {
                                                    timelist.get(position).setIsthumbs(0);
                                                    timelist.get(position).setThumbsCount(timelist.get(position).getThumbsCount() - 1);
                                                }
                                                timeAdapter.notifyDataSetChanged();
                                            }else if (jsonObject.getInt("returnCode") == 400){
                                                Intent intent=new Intent(AuthShuPingActivity.this, LoginActivity.class);
                                                startActivity(intent);
                                                showToast(jsonObject.getString("msg"));
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                });
                        break;
                }
            }
        });
        refreshBookdatasmuchshuping.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                page++;
                initData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                timelist.clear();
                hotlist.clear();
                page = 1;
                initData();
                initDataHot();
            }
        });
        tocommentshuping.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (String.valueOf(editable).length() >= 100) {
                    showToast("评论内容不能超过100个字");
                }
            }
        });
    }

    private void initDataHot() {
        OkHttpUtils.post(HttpManager.IP + "/comm-HotCommentInfo")

                .params("bookid", bookId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        refreshBookdatasmuchshuping.finishRefresh();
                        refreshBookdatasmuchshuping.finishLoadMore();
                        Gson gson = new Gson();
                        try {
                            hotbookconbean = gson.fromJson(s, HotConmmentBean.class);
                            if (200 == hotbookconbean.getReturnCode()) {
                                if (hotbookconbean.getData().size() > 0) {
                                    hotlist.addAll(hotbookconbean.getData());
                                    hotAdapter.notifyDataSetChanged();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @OnClick({R.id.back_UserShuping, R.id.sendshuping})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_UserShuping:
                setResult(8);
                goBack();
                break;
            case R.id.sendshuping:
                if (!UserManageBean.isLogin(AuthShuPingActivity.this)){
                    return;
                }
                if (tocommentshuping.getText().toString().equals("")) {
                    showToast("评论内容不能为空");
                } else {
                    OkHttpUtils.post(HttpManager.IP + "/add-getcomminfo")

                            .params("bookId", bookId)
                            .params("commentContext", tocommentshuping.getText().toString())
                            .params("userName", UserManageBean.userBean.getPseudonym())
                            .params("bookName", bookName)
                            .execute(new StringCallback() {
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(s);
                                        if (jsonObject.getInt("returnCode") == 200) {
                                            Tool.hideKeybard(AuthShuPingActivity.this);
                                            tocommentshuping.setText("");
                                            timelist.clear();
                                            page = 1;
                                            initData();
                                        }else if (jsonObject.getInt("returnCode") == 400){
                                            Intent intent=new Intent(AuthShuPingActivity.this,LoginActivity.class);
                                            startActivity(intent);
                                        }
                                        showToast(jsonObject.getString("msg"));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 8) {
            hotlist.clear();
            initDataHot();
        }
    }
}
